package com.heima.user.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.XAConnection;

/**
 * @作者 itcast
 * @创建日期 2021/9/20 11:35
 **/
@Service
@Slf4j
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        // 1. 检查参数
        dto.checkParam(); // 分页参数
        // 2. 封装查询条件
        // 2.1  分页条件
        IPage<ApUserRealname> pageReq = new Page<>(dto.getPage(),dto.getSize());
        // 2.2  status
        LambdaQueryWrapper<ApUserRealname> queryWrapper = Wrappers.<ApUserRealname>lambdaQuery();
        // 如果status不为空 按照状态查询
        queryWrapper.eq(dto.getStatus()!=null,ApUserRealname::getStatus,dto.getStatus());
        // 3. 执行查询
        IPage<ApUserRealname> pageResult = this.page(pageReq, queryWrapper);
        // 4. 封装结果
        return new PageResponseResult(dto.getPage(),dto.getSize(),pageResult.getTotal(),pageResult.getRecords());
    }
    @Autowired
    ApUserMapper apUserMapper;
    //    @Transactional
    // 开启全局事务
    @GlobalTransactional(rollbackFor = Exception.class,timeoutMills = 100000)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        // 1. 检查参数
        // 1.1 检查id
        if(dto.getId() == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"实名认证id不能为空");
        }
        // 1.2 根据id 查询实名认证信息
        ApUserRealname userRealname = getById(dto.getId());
        // 1.3 检查状态  1待审核 2失败 9通过
        if(!userRealname.getStatus().equals(AdminConstants.WAIT_AUTH)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"实名认证状态错误");
        }
        // 1.4 查询关联的apUser信息
        ApUser apUser = apUserMapper.selectById(userRealname.getUserId());
        if(apUser == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证关联的app用户信息不存在");
        }
        // 2. 修改实名认证的状态
        userRealname.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            userRealname.setReason(dto.getMsg());
        }
        updateById(userRealname);
        // 3. 判断是否为通过 状态: 9
        if(AdminConstants.PASS_AUTH.equals(userRealname.getStatus())){
            // 3.1  远程开通自媒体账户
            WmUser wmUser = createWmUser(apUser); // 返回自媒体账户
            // 3.2  创建作者信息  // ap_user   wm_user
            createAuthor(wmUser,apUser);
        }

        System.out.println(1/0);
        return ResponseResult.okResult();
    }

    @Autowired
    ArticleFeign articleFeign;


    private void createAuthor(WmUser wmUser, ApUser apUser) {
        // 1.  远程查询作者信息是否存在
        ResponseResult<ApAuthor> authorResult  = articleFeign.findByUserId(apUser.getId());
        if (authorResult.getCode().intValue()!=0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,authorResult.getErrorMessage());
        }
        ApAuthor author = authorResult.getData();
        if(author!=null){ // 自媒体账户已经有了
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"对应的作者信息已经存在");
        }
        author = new ApAuthor();
        author.setName(apUser.getName());
        author.setType(2);
        author.setUserId(apUser.getId());
        author.setCreatedTime(new Date());
        author.setWmUserId(wmUser.getId());
        // 2. 如果不存在 ，创建作者信息
        ResponseResult saveResult = articleFeign.save(author);
        if (saveResult.getCode().intValue()!=0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,saveResult.getErrorMessage());
        }
    }


    @Autowired
    WemediaFeign wemediaFeign;

    /**
     * 远程创建自媒体账户
     * @param apUser
     * @return
     */
    private WmUser createWmUser(ApUser apUser) {
        // 1. 查询关联自媒体账户是否已经创建
        ResponseResult<WmUser> wmUserResult = wemediaFeign.findByName(apUser.getName());
        if (wmUserResult.getCode().intValue() != 0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,wmUserResult.getErrorMessage());
        }
        WmUser wmUser = wmUserResult.getData();
        if(wmUser!=null){ // 自媒体账户已经有了
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"对应的自媒体账户已经存在");
        }
        wmUser = new WmUser(); // 创建自媒体账户
        wmUser.setApUserId(apUser.getId());
        wmUser.setName(apUser.getName());
        wmUser.setPassword(apUser.getPassword());
        wmUser.setSalt(apUser.getSalt());
        wmUser.setImage(apUser.getImage());
        wmUser.setPhone(apUser.getPhone());
        wmUser.setStatus(9); // 正常
        wmUser.setType(0);
        wmUser.setCreatedTime(new Date());
        ResponseResult<WmUser> saveResult = wemediaFeign.save(wmUser);
        if (saveResult.getCode().intValue()!=0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,saveResult.getErrorMessage());
        }
        // 2. 创建自媒体账户
        return saveResult.getData();// 已经设置了id的wmUser对象
    }
}